#include "modifybookface.h"
#include "ui_modifybookface.h"

modifyBookface::modifyBookface(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::modifyBookface)
{
    ui->setupUi(this);

    appDir = QCoreApplication::applicationDirPath();
}

void modifyBookface::on_sureBtn_clicked()
{
    QFile bookfile(appDir + "/bookInfo.txt");
    if (bookfile.exists() == false)
    {
        QMessageBox::warning(this, "bookInfo文件打开", "bookInfo文件不存在");
        return;
    }

    bookfile.open(QIODevice::ReadOnly);

    QStringList lines;  //字符串链表

    while (bookfile.atEnd() == false) //文件没结束
    {
        QString line = bookfile.readLine(); // 读取每一行字符串
        lines.append(line);    //读取每一行字符串到链表中
    }
    bookfile.close();

    // 查找并修改目标行
    bool found = false;
    for (int i = 0; i < lines.size(); ++i)
    {
        QString data = lines[i];
        if (lines[i].split("+")[0] == ui->le_prevbookname->text() && lines[i].split("+")[1] == ui->le_prevauthor->text() && lines[i].split("+")[2].split("\n")[0] == ui->le_prevcnt->text())
        {
            lines[i] = ui->le_afterbookname->text() + "+" + ui->le_afterauthor->text() + "+" + ui->le_aftercnt->text() + "\n"; // 修改该行
            found = true;
            break; // 只需要修改第一个匹配项
        }
    }

    if (!found) //没找到
    {
        QMessageBox::warning(this, "修改失败", "该书信息有误");
        return;
    }
    else
    {
        QMessageBox::warning(this, "修改成功", "该图书信息已修改");
        ui->le_prevbookname->clear();
        ui->le_prevauthor->clear();
        ui->le_prevcnt->clear();
        ui->le_afterbookname->clear();
        ui->le_afterauthor->clear();
        ui->le_aftercnt->clear();
        this->hide();
    }

    bookfile.open(QIODevice::WriteOnly);

    QTextStream out(&bookfile);
    // 设置编码为 UTF-8
    out.setCodec("UTF-8");
    for (int idx = 0; idx < lines.size(); idx++)
    {
        out << lines[idx];
    }

    bookfile.close();

    emit updataView();
}

void modifyBookface::on_cancelBtn_clicked()
{
    ui->le_prevbookname->clear();
    ui->le_prevauthor->clear();
    ui->le_prevcnt->clear();
    ui->le_afterbookname->clear();
    ui->le_afterauthor->clear();
    ui->le_aftercnt->clear();
    this->hide();
}

modifyBookface::~modifyBookface()
{
    delete ui;
}
